package com.mapreduct;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.io.LongWritable;
 
import java.io.IOException;
import java.util.Iterator;

 
public class WordCount {
 
    public static class TokenizerMapper
            extends Mapper<LongWritable, Text, Text, PhoneBean> {
 
        public void map(LongWritable key, Text value, Context context
        ) throws IOException, InterruptedException {
            String line = value.toString();
            String[] fields = line.split("\t");
            String phoneNum = fields[1];
            long upFlow = Long.parseLong(fields[fields.length - 3]);
            long downFlow = Long.parseLong(fields[fields.length - 2]);
            PhoneBean bean = new PhoneBean(upFlow, downFlow);
            context.write(new Text(phoneNum), bean);
        }
    }
 
    public static class IntSumReducer
            extends Reducer<Text, PhoneBean, Text, PhoneBean> {
        
        public void reduce(Text key, Iterable<PhoneBean> values,
                           Context context
        ) throws IOException, InterruptedException {
            Iterator<PhoneBean> iterator = values.iterator();
            long upFlow = 0;
            long downFlow = 0;
            while (iterator.hasNext()) {
                PhoneBean bean = iterator.next();
                upFlow += bean.getUpflow();
                downFlow += bean.getDownflow();
            }
            PhoneBean total = new PhoneBean(upFlow, downFlow);
            context.write(key, total);
        }
    }
 
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "word count");
        job.setJarByClass(WordCount.class);
        job.setMapperClass(TokenizerMapper.class);
        job.setCombinerClass(IntSumReducer.class);
        job.setReducerClass(IntSumReducer.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(PhoneBean.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(PhoneBean.class);


        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
